#!/usr/bin/env node

import { ForexDanaClassifier } from '../services/ForexDanaClassifier';
import { ExtractionResult } from '../types';
import * as fs from 'fs';
import * as path from 'path';

/**
 * 显示帮助信息
 */
function showHelp() {
  console.log(`
ForexDana翻译分类工具

用法: classify-translations [选项] <提取结果文件>

选项:
  -h, --help              显示帮助信息
  -o, --output <目录>     指定输出目录 (默认: 与输入文件同目录)
  -f, --format <格式>     指定输出格式 (json 或 excel, 默认: json)
  -m, --module           使用模块化结构输出 (默认: 关闭)
  -r, --references       处理跨模块引用 (默认: 关闭，需开启模块化)
  `);
}

/**
 * 解析命令行参数
 */
function parseArgs() {
  const args = process.argv.slice(2);
  const options = {
    help: false,
    outputDir: '',
    format: 'json',
    module: false,
    references: false,
    inputFile: ''
  };

  for (let i = 0; i < args.length; i++) {
    const arg = args[i];

    if (arg === '-h' || arg === '--help') {
      options.help = true;
    } else if (arg === '-o' || arg === '--output') {
      if (i + 1 < args.length) {
        options.outputDir = args[++i];
      }
    } else if (arg === '-f' || arg === '--format') {
      if (i + 1 < args.length) {
        const format = args[++i].toLowerCase();
        if (format === 'json' || format === 'excel') {
          options.format = format;
        } else {
          console.error(`错误: 不支持的格式 "${format}"`);
          process.exit(1);
        }
      }
    } else if (arg === '-m' || arg === '--module') {
      options.module = true;
    } else if (arg === '-r' || arg === '--references') {
      options.references = true;
    } else if (!arg.startsWith('-')) {
      options.inputFile = arg;
    }
  }

  return options;
}

/**
 * 主函数
 */
async function main() {
  const options = parseArgs();
  
  // 显示帮助
  if (options.help) {
    showHelp();
    process.exit(0);
  }
  
  // 检查输入文件
  if (!options.inputFile) {
    console.error('错误: 必须提供提取结果文件路径');
    showHelp();
    process.exit(1);
  }
  
  if (!fs.existsSync(options.inputFile)) {
    console.error(`错误: 找不到文件 "${options.inputFile}"`);
    process.exit(1);
  }
  
  // 确定输出目录
  const outputDir = options.outputDir || path.dirname(options.inputFile);
  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
    console.log(`创建输出目录: ${outputDir}`);
  }
  
  try {
    // 读取翻译提取结果
    console.log('读取翻译提取结果...');
    const resultContent = fs.readFileSync(options.inputFile, 'utf-8');
    const extractionResult: ExtractionResult = JSON.parse(resultContent);
    
    // 创建ForexDana分类器
    const classifier = new ForexDanaClassifier();
    
    // 选择处理方式
    if (options.module) {
      console.log('使用模块化结构进行分类...');
      const result = classifier.transformToModules(extractionResult.translations);
      
      // 生成模块化报告
      const report = classifier.generateModuleReport(extractionResult.translations);
      
      // 保存报告
      fs.writeFileSync(
        path.join(outputDir, 'module-report.txt'),
        report,
        'utf-8'
      );
      
      // 保存模块树
      fs.writeFileSync(
        path.join(outputDir, 'module-tree.json'),
        JSON.stringify(result.moduleTree, null, 2),
        'utf-8'
      );
      
      // 保存统计信息
      fs.writeFileSync(
        path.join(outputDir, 'module-statistics.json'),
        JSON.stringify({
          transform: result.transformStatistics,
          reference: result.referenceStatistics
        }, null, 2),
        'utf-8'
      );
      
      console.log('模块化分类完成！');
      console.log(`模块树已保存到: ${path.join(outputDir, 'module-tree.json')}`);
      console.log(`报告已保存到: ${path.join(outputDir, 'module-report.txt')}`);
    } else {
      // 原有的分类逻辑
      console.log('进行基础分类...');
      const classificationResult = classifier.classify(extractionResult.translations);
      
      // 生成分类报告
      const report = classifier.generateReport(classificationResult);
      
      // 保存分类报告
      fs.writeFileSync(
        path.join(outputDir, 'classification-report.txt'),
        report,
        'utf-8'
      );
      
      // 保存分类结果
      // 构建层次化的分类结果
      const hierarchicalResult = {
        infrastructure: Object.entries(classificationResult.infrastructureTranslations).map(([module, translations]) => ({
          module,
          translations
        })),
        business: Object.entries(classificationResult.businessTranslations).map(([module, translations]) => ({
          module,
          translations
        })),
        unclassified: classificationResult.unclassifiedTranslations,
        statistics: classificationResult.statistics
      };
      
      // 保存完整分类结果
      fs.writeFileSync(
        path.join(outputDir, 'classified-translations.json'),
        JSON.stringify(hierarchicalResult, null, 2),
        'utf-8'
      );
      
      // 创建目录结构
      const infrastructureDir = path.join(outputDir, 'infrastructure');
      if (!fs.existsSync(infrastructureDir)) {
        fs.mkdirSync(infrastructureDir, { recursive: true });
      }
      
      const businessDir = path.join(outputDir, 'business');
      if (!fs.existsSync(businessDir)) {
        fs.mkdirSync(businessDir, { recursive: true });
      }
      
      // 保存基础设施类翻译
      for (const [dir, translations] of Object.entries(classificationResult.infrastructureTranslations)) {
        if (translations.length > 0) {
          const filePath = path.join(infrastructureDir, `${dir}.json`);
          fs.writeFileSync(
            filePath,
            JSON.stringify(translations, null, 2),
            'utf-8'
          );
          console.log(`- 已保存 ${translations.length} 条 ${dir} 翻译到 ${filePath}`);
        }
      }
      
      // 保存业务功能类翻译
      for (const [module, translations] of Object.entries(classificationResult.businessTranslations)) {
        if (translations.length > 0) {
          const filePath = path.join(businessDir, `${module}.json`);
          fs.writeFileSync(
            filePath,
            JSON.stringify(translations, null, 2),
            'utf-8'
          );
          console.log(`- 已保存 ${translations.length} 条 ${module} 翻译到 ${filePath}`);
        }
      }
      
      // 保存未分类翻译
      if (classificationResult.unclassifiedTranslations.length > 0) {
        const filePath = path.join(outputDir, 'unclassified.json');
        fs.writeFileSync(
          filePath,
          JSON.stringify(classificationResult.unclassifiedTranslations, null, 2),
          'utf-8'
        );
        console.log(`- 已保存 ${classificationResult.unclassifiedTranslations.length} 条未分类翻译到 ${filePath}`);
      }
      
      // 如果是Excel格式，生成Excel文件
      if (options.format.toLowerCase() === 'excel') {
        console.log('生成Excel文件...');
        // 需要额外安装xlsx库: npm install xlsx
        try {
          // 使用动态导入避免直接依赖
          const xlsxModule = await import('xlsx').catch(() => {
            throw new Error('生成Excel需要xlsx库，请先安装: npm install xlsx');
          });
          
          // 创建工作簿
          const workbook = xlsxModule.utils.book_new();
          
          // 添加基础设施类工作表
          const infrastructureData: any[] = [];
          for (const [dir, translations] of Object.entries(classificationResult.infrastructureTranslations)) {
            translations.forEach(t => {
              infrastructureData.push({
                '模块': dir,
                '键名': t.key,
                '文件': t.file,
                '行号': t.line,
                '上下文': t.context,
                '频率': t.frequency,
                '已定义': t.isDefined ? '是' : '否',
                '简化路径': classifier.extractSimplifiedPath(t.file) || ''
              });
            });
          }
          
          if (infrastructureData.length > 0) {
            const infrastructureSheet = xlsxModule.utils.json_to_sheet(infrastructureData);
            xlsxModule.utils.book_append_sheet(workbook, infrastructureSheet, '基础设施类');
          }
          
          // 添加业务功能类工作表
          const businessData: any[] = [];
          for (const [module, translations] of Object.entries(classificationResult.businessTranslations)) {
            translations.forEach(t => {
              businessData.push({
                '模块': module,
                '键名': t.key,
                '文件': t.file,
                '行号': t.line,
                '上下文': t.context,
                '频率': t.frequency,
                '已定义': t.isDefined ? '是' : '否',
                '简化路径': classifier.extractSimplifiedPath(t.file) || ''
              });
            });
          }
          
          if (businessData.length > 0) {
            const businessSheet = xlsxModule.utils.json_to_sheet(businessData);
            xlsxModule.utils.book_append_sheet(workbook, businessSheet, '业务功能类');
          }
          
          // 添加统计工作表
          const statsData = [
            { '分类': '总翻译条目', '数量': classificationResult.statistics.totalCount, '百分比': '100%' },
            { 
              '分类': '基础设施类', 
              '数量': classificationResult.statistics.infrastructureCount, 
              '百分比': `${((classificationResult.statistics.infrastructureCount / classificationResult.statistics.totalCount) * 100).toFixed(1)}%` 
            },
            { 
              '分类': '业务功能类', 
              '数量': classificationResult.statistics.businessCount, 
              '百分比': `${((classificationResult.statistics.businessCount / classificationResult.statistics.totalCount) * 100).toFixed(1)}%` 
            },
            { 
              '分类': '未分类条目', 
              '数量': classificationResult.statistics.unclassifiedCount, 
              '百分比': `${((classificationResult.statistics.unclassifiedCount / classificationResult.statistics.totalCount) * 100).toFixed(1)}%` 
            }
          ];
          
          const statsSheet = xlsxModule.utils.json_to_sheet(statsData);
          xlsxModule.utils.book_append_sheet(workbook, statsSheet, '统计摘要');
          
          // 保存Excel文件
          const excelPath = path.join(outputDir, 'classified-translations.xlsx');
          xlsxModule.writeFile(workbook, excelPath);
          console.log(`已生成Excel文件: ${excelPath}`);
        } catch (error: any) {
          console.error('生成Excel文件失败:', error.message);
        }
      }
      
      // 打印摘要
      console.log('\n分类摘要:');
      console.log(`总翻译条目: ${classificationResult.statistics.totalCount}`);
      console.log(`基础设施类: ${classificationResult.statistics.infrastructureCount} (${((classificationResult.statistics.infrastructureCount / classificationResult.statistics.totalCount) * 100).toFixed(1)}%)`);
      console.log(`业务功能类: ${classificationResult.statistics.businessCount} (${((classificationResult.statistics.businessCount / classificationResult.statistics.totalCount) * 100).toFixed(1)}%)`);
      console.log(`未分类条目: ${classificationResult.statistics.unclassifiedCount} (${((classificationResult.statistics.unclassifiedCount / classificationResult.statistics.totalCount) * 100).toFixed(1)}%)`);
      
      console.log(`\n分类报告已保存到: ${path.join(outputDir, 'classification-report.txt')}`);
      console.log('分类完成!');
    }
    
  } catch (error) {
    console.error('翻译分类过程中出错:', error);
    process.exit(1);
  }
}

// 执行主函数
main().catch(error => {
  console.error('程序执行出错:', error);
  process.exit(1);
}); 